import json
import time

import requests
from Util.EncoderUtil import encode, decode, key_bytes


def get_authorization():
    # 使用当前时间戳
    timestamp = int(time.time() * 1000)
    t = f'{{"token":"","platform":3,"version":"2.0.5","device":"FAAE6E21-013F-42D1-B722-599DE3DC340F","timestamp":{timestamp}}}'
    return encode(t, key_bytes)

async def get_token(username, password):
    access = f'{{"schoolCode":11505,"code":"{username}","password":"{password}"}}'
    params = encode(access)
    try:
        # 发起请求
        response = requests.get(
            "https://ekta.jjvu.jx.cn/api/app/client/v1/token",
            params={"params": params},
            headers={"Authorization": get_authorization()}
        )
        # 解密响应
        decrypted_string = decode(response.text)
        if not decrypted_string:
            raise Exception("解密结果为空字符串")
        # 解析JSON
        decrypted_json = json.loads(decrypted_string)
        # 提取token
        token = decrypted_json["data"]["access_token"]
        if not token:
            raise Exception("未能从解密后的数据中提取到 access_token")
        else:
            print(f'获取token成功  ')
        return token
    except Exception as e:
        print(f"getToken 函数内部错误: {e}")
        return None

